﻿using Sustainalytics.Entities.ESGRatings;
using Sustainalytics.ESG.Entities;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sustainalytics.ESGRatings.BusinessLogic
{
    public class FocusedRatingsAssessmentManager
    {
        private readonly List<EsgFocusThresholds> thresholds;

        private readonly AssessmentsManager _translator = new AssessmentsManager();

        public FocusedRatingsAssessmentManager(IEnumerable<EsgFocusThresholds> thresholds)
        {
            if (thresholds == null)
            {
                throw new ArgumentNullException(nameof(thresholds));
            }

            this.thresholds = thresholds.OrderBy(x => x.Type).ThenByDescending(x => x.LowerBound).ToList();
        }

        public static RPAssessment GetAssessment(double companyScore, EsgFocusThresholds[] thresholds, ThresholdType type = ThresholdType.Overall)
        {
            return new FocusedRatingsAssessmentManager(thresholds).GetAssessment(companyScore, type);
        }

        public RPAssessment GetAssessment(RPCompanyESGComputationResult score, Func<RPCompanyESGComputationResult, double> expression, ThresholdType type)
        {
            var companyScore = expression(score);
            return this.GetAssessment(companyScore, type);
        }

        private RPAssessment GetAssessment(double companyScore, ThresholdType type)
        {
            var thresholdIndex = thresholds.FindIndex(t => t.LowerBound <= companyScore && companyScore < t.UpperBound && type == t.Type);
            if (thresholdIndex >= 0)
            {
                var assessment = _translator.GetById(thresholdIndex);
                return new RPAssessment { Id = assessment != null ? assessment.Id : 0, Name = assessment?.Name };
            }

            return new RPAssessment();
        }
    }
}
